Skip to main content

Conditions

Try PowerShell - Let's branch out!

There are certain conditions that need to be met before some part of your script executes or when you need to control the flow of your script. When that happens, you could use the conditional statment in your script.

If

If ($true){ 
#do something
}

The script logic here is very simple. Let's try, check whether the folder path exists. If it does, write the message.

If(Test-Path -Path 'C:\temp'){
Write-Output "The folder exists!"
}

If Else

The following script added the else statement. The condition is: if the folder doesn't exist, create the folder.

If(Test-Path -Path 'C:\temp'){
Write-Output "The folder exists!"
}
Else {
Write-Warning "The folder does not exist!"
Write-Output "Creating the folder..."
New-Item -Path 'C:\temp' -Force
}

If you come across the logic like this you could contract it by simply using -Not within the if statement.

If(-Not(Test-Path -Path 'C:\temp')){
New-Item -Path 'C:\temp' -Force
}

If Elseif Else

[Int]$Time = Get-Date -UFormat %H
If($Time -in 5..11){
"Good Morning"
}
ElseIf($Time -in 12..17){
"Good Afternoon"
}
ElseIf($Time -in 18..23){
"Good Evening"
}
Else{ "Haven't you slept yet?" }

You could have as many ElseIf as your script logic requires. The script will test the condition from the top to the bottom till it meets the condition. However, this can affect the performance of your script. This is where the Switch statement comes in handy.

Switch

[Int]$Time = Get-Date -UFormat %H
Switch($Time){
{$_ -in 5..11} {"Good Morning"; break}
{$_ -in 12..17}{"Good Afternoon"; break}
{$_ -in 18..23}{"Good Evening"; break}
default { "Haven't you slept yet?" }
}

Switch statement can give you some performance boost to your script. But be aware of the keyword break within the Switch statement. If you do not put it after each statement or expression, it will continue to run the next statement until it can come out of the switch statement. You do not need to put break keyword in the last option.

Ternary

Ternary Operator Syntax: (Condition)? "true expression" : "false expression"
This is simply the shortened version of If(Condition){"True expresion"}Else{"False expression"}

#This works on PowerShell v7 or higher
(Test-Path -Path 'C:\temp') ? "Path Exists" : "Path not found!"

#For PowerShell v5 or older
@{$true="Path Exists";$false="Path not found!"}[$(Test-Path -Path 'C:\temp')]
Take away

The two dots between the number mean range. ie. 1..5 will render 1,2,3,4,5.
$_ is the alias of automatic variable $PSItem. It stores the current value of your variable where the script is at. It is normal to use If statement within another If statement as nestsed if statement in your script.